#include <iostream>
#include <string>
#include <sstream>
#include <jsoncpp/json/json.h>

// void serialize()
// {
//     const char* name = "小明";
//     int age = 18;
//     const char* sex = "男";
//     float score[3] = {88, 77.5, 66};

//     Json::Value student;
//     student["姓名"] = name;
//     student["年龄"] = age;
//     student["性别"] = sex;
//     student["成绩"].append(score[0]);
//     student["成绩"].append(score[1]);
//     student["成绩"].append(score[2]);

//     Json::Value fav;
//     fav["书籍"] = "西游记";
//     fav["运动"] = "台球";
//     student["爱好"] = fav;
    
//     //先实例化一个工厂类对象
//     Json::StreamWriterBuilder swb;
//     //通过工厂类对象生产派生类对象
//     Json::StreamWriter* sw = swb.newStreamWriter();
//     sw->write(student,&std::cout);
//     std::cout<<std::endl;

//     delete sw;
// }

//实现数据序列化
bool serialize(const Json::Value& val, std::string& body)
{
    std::stringstream ss;

    //先实例化一个工厂类对象
    Json::StreamWriterBuilder swb;
    //通过工厂类对象生产派生类对象
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
    int ret = sw->write(val,&ss);
    if(ret != 0)
    {
        std::cout<<"json seralize failed\n"<<std::endl;
        return false;
    }
    body = ss.str();
    return true;
}

//实现JSON字符串的反序列化
bool unserialize(const std::string& body, Json::Value& val)
{
    //实例化工厂对象
    Json::CharReaderBuilder crb;
    //实例化CharReader对象
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    std::string errs;
    bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &errs);
    if(ret == false)
    {
        std::cout<< "json unserialize failed:"<<errs<<std::endl;
        return false;
    }
    return true;
}


int main()
{   
    const char* name = "小明";
    int age = 18;
    const char* sex = "男";
    float score[3] = {88, 77.5, 66};

    Json::Value student;
    student["姓名"] = name;
    student["年龄"] = age;
    student["性别"] = sex;
    student["成绩"].append(score[0]);
    student["成绩"].append(score[1]);
    student["成绩"].append(score[2]);

    Json::Value fav;
    fav["书籍"] = "西游记";
    fav["运动"] = "台球";
    student["爱好"] = fav;

    std::string body;
    serialize(student, body);
    std::cout<< body << std::endl;
    return 0;
}